import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_ITEM, INIT_DATA } from './actionTypes';

const defaultState = {
  inputValue: '',
  list: []
}

//reducer 可以接收state， 但是绝不能直接修改
export default (state = defaultState, action) => {
  if (action.type === CHANGE_INPUT_VALUE) {
    const newState = JSON.parse(JSON.stringify(state)); //深拷贝
    newState.inputValue = action.value;
    return newState; //固定写法
  }

  if (action.type === ADD_TODO_ITEM) {
    const newState = JSON.parse(JSON.stringify(state)); //深拷贝
    newState.list.push(newState.inputValue);
    newState.inputValue = '';
    return newState; //固定写法
  }

  if (action.type === DELETE_ITEM) {
    const newState = JSON.parse(JSON.stringify(state)); //深拷贝
    newState.list.splice(action.index, 1);
    return newState; //固定写法
  }

  if (action.type === INIT_DATA) {
    const newState = JSON.parse(JSON.stringify(state)); //深拷贝
    newState.list = action.data;
    return newState; //固定写法
  }

  return state;
}